package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;

@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Autowired
    private AntPathMatcher antPathMatcher;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        HashSet<String> URIs = new HashSet<>();
        URIs.add("/employee/login");
        URIs.add("/employee/logout");
        URIs.add("/backend/**");
        URIs.add("/front/**");
        HttpSession session = request.getSession();
        for (String URI : URIs) {
            if (session.getAttribute("employee")!=null||
                    antPathMatcher.match(URI, uri)) {
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    @Override
    public void destroy() {

    }
}
